package com.shuaitao.newsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuaitao.newsystem.bean.NewsUsers;
import com.shuaitao.newsystem.service.NewsUsersService;
import com.shuaitao.newsystem.utils.JwtUtil;
import com.shuaitao.newsystem.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private NewsUsersService newsUsersService;

    @PostMapping("/toLogin")
    @ResponseBody
    public R login(@NotBlank @RequestParam("uname") String uname ,@NotBlank @RequestParam("upwd") String upwd, HttpSession session) {
        R r = newsUsersService.login(uname,upwd,session);

        return r;
    }
    @GetMapping("/loginOut")
    @ResponseBody
    public R loginOut(HttpSession session) {
        session.invalidate();
        return R.ok();
    }

    @GetMapping("/toRegister")
    public String toRegister() {
        return "newspages/register";
    }

    @PostMapping("/register")
    @ResponseBody
    public R register(@NotBlank @RequestParam("username")String name,@NotBlank @RequestParam("password") String password) {
        NewsUsers newsUsers = new NewsUsers();
        int username = newsUsersService.count(new QueryWrapper<NewsUsers>().eq("uname", name));
        if (username > 0) {
            return R.error(101,"账号重复！！！");
        }
        newsUsers.setUpwd(password);
        newsUsers.setUname(name);
        newsUsersService.save(newsUsers);
        return R.ok();
    }
}
